package com.wwlwxg.spring_security.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wwlwxg.spring_security.entity.Users;
import com.wwlwxg.spring_security.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {

  @Autowired
  private UsersMapper usersMapper;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    // 调用 usersMapper 方法，根据用户名查询数据库
    QueryWrapper<Users> wrapper = new QueryWrapper<>();
    wrapper.eq("username", username);

    Users users = usersMapper.selectOne(wrapper);

    // 判断
    if(users == null) {
      throw new UsernameNotFoundException("用户名不存在");
    }

    List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
    return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), auths);
  }
}
